﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IMPACT.Models;
using System.Web.Security;

namespace IMPACT.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Models.LoginModel user)
        {
            if (ModelState.IsValid)
            {
                if (CredentialCheck(user.EmailAdress, user.Password))
                {
                    FormsAuthentication.SetAuthCookie(user.EmailAdress, false);
                    return RedirectToAction("Index","Home");
                }
                ModelState.AddModelError("", "Login Details are incorrect");
            }
            return View(user);
        }

        [HttpPost]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
     
        }

        private bool CredentialCheck(string email, string password)
        {
            bool valid=false;
            using(var db = new ImpactEntities())
            {
                var user = db.Users.FirstOrDefault(u=>u.Email == email);
                if (user != null)
                {
                    if (user.Password == password)
                    {
                        valid = true;
                    }
                }
            }
            return valid;
        }
    }
}
